import { useEffect, useState } from 'react';
import '../index.less';
import { Button, Cascader, Form, message, Modal, Popconfirm, Table } from 'antd';
import {
  getManagerCityList, addManagerCity, delManagerCity
} from '../services'
import { useRequest } from 'ahooks';
import { PAGINATION_CONFIG } from '@/constants';
import { queryCityOptions2 } from '@/services/common';

export interface CityModalProps {
  open: boolean
  onCancel?: (refresh?: boolean) => void
  infoId?: number
}

const StubEditPage: React.FC<CityModalProps> = (props) => {
  const [editForm] = Form.useForm()
  const [params, setParams] = useState<any>({pageNum: 1, pageSize: 10})
  const { data, loading, refresh } = useRequest(() => getManagerCityList(params), {
    ready: !!params.infoId,
    refreshDeps: [params],
  })
  const addReq = useRequest(addManagerCity, {manual: true})
  const delReq = useRequest(delManagerCity, {manual: true})
  const cityOptions = useRequest(queryCityOptions2)
  const onCancel = (refresh?: boolean) => {
    editForm.resetFields()
    props.onCancel?.(refresh)
  }

  const getCityInfo = (record: any) => {
    const result = {
      province: '',
      city: '',
      district: '',
    }
    cityOptions.data?.data.some(province => {
      return province.children.some(city => {
        return city.children.some(district => {
          if (district.value === record.cityId) {
            result.province = province.label
            result.city = city.label
            result.district = district.label
            return true
          }
          return false
        })
      })
    })
    return result
  }

  const add = () => {
    let cityInfo: any
    Modal.confirm({
      title: '选择城市',
      content: <Cascader
        loading={cityOptions.loading}
        options={cityOptions.data?.data}
        style={{width: 320}}
        placeholder='请选择'
        onChange={(val, val2) => cityInfo = val2}
      />,
      onOk: async () => {
        if (!cityInfo) {
          message.error('请选择城市')
          return Promise.reject()
        }
        return addReq.runAsync({
          infoId: props.infoId,
          province: cityInfo[0].label,
          city: cityInfo[1].label,
          district: cityInfo[2].label,
          cityId: cityInfo[2].value,
        }).then(refresh)
      }
    })
  }

  const del = (record: any) => {
    return delReq.runAsync({infoId: props.infoId, cityId: record.cityId}).then(refresh)
  }

  useEffect(() => {
    if (props.open) {
      setParams({infoId: props.infoId, pageNum: 1, pageSize: 10})
    }
    else {
      setParams({pageNum: 1, pageSize: 10})
    }
  }, [props.open])
  
  return (
    <Modal
      title='城市权限'
      className='container'
      open={props.open}
      onCancel={() => onCancel()}
      width={880}
      footer={[<Button key='cancelBtn' onClick={() => onCancel()}>关闭</Button>]}
    >
      <Button type='primary' onClick={add} style={{marginBottom: 12}}>添加城市</Button>
      <Table
        rowKey={'id'}
        loading={loading}
        dataSource={data?.data || []}
        columns={[
          {title: '省', dataIndex: 'province'},
          {title: '市', dataIndex: 'city'},
          {title: '区', dataIndex: 'district'},
          {title: '操作', key: 'operations', render: (val, record) => {
            return <Popconfirm title='确认删除吗?' onConfirm={() => del(record)}>
              <a>删除</a>
            </Popconfirm>
          }}
        ]}
         pagination={{
          ...PAGINATION_CONFIG,
          current: params.pageNum,
          pageSize: params.pageSize,
          total: data?.totalCount || 0,
          onChange: (page, pageSize) => {
            setParams({
              ...params,
              pageNum: page === params.pageNum ? 1 : page,
              pageSize,
            })
          }
        }}
      />
    </Modal>
  );
};

export default StubEditPage;
